package com.hongxun.design.sqlite.dao;

import android.content.Context;

import com.hongxun.design.sqlite.DatabaseHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cqcqwu on 2018/03/29.
 */

public abstract class BaseDao<T extends Object> {
    protected Context mContext;
    protected Dao<T, Integer> dao;
    protected QueryBuilder<T, Integer> builder;
    protected DatabaseHelper helper;

    public BaseDao(Context context) {
        this.mContext = context;
        try {
            helper = DatabaseHelper.getHelper(context);
            dao = helper.getDao(getClassByT());
            builder = dao.queryBuilder();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Class getClassByT() {
        return (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    public void insert(T t) {
        try {
            dao.create(t);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void delete(T t) {
        try {
            dao.delete(t);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void update(T t) {
        try {
            dao.update(t);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //任意列与值查询
    public List<T> getByClumAndValue(String cloum, Object value) {
        List<T> tList = null;
        try {
            tList = builder.where().eq(cloum, value).query();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (tList == null) tList = new ArrayList<>();
        }
        return tList;
    }
}
